import { OptionsApi } from "@/service/options-api";
import { ProjectService } from "@/service/projects-api";

/**
 * 更新脚本
 * @returns 
 */
export async function checkAndUpdateScripts() {
    
    const conf = await OptionsApi.getConfig().catch(() => undefined);
    if (conf && conf.autoUpdateScripts === false) {
        return
    }
    console.log('更新检查')
    const data = await ProjectService.list().catch(() => []);
    if (data.length === 0) {
        return
    }
    for (const item of data) {
        updateScriptForVersion(item)
    }
}

function updateScriptForVersion(item: ProjectItem) {
    if (!item.url) {
        return
    }
    console.log('检查更新',item.name)
    const id = item.id + ''
    const enabled = item.enabled
    fetch(`${item.url}?v=${item.version}`).then(res => res.json()).then(data => {
        if (data.code === 200) {
            console.log('需要更新',item.name)
            return fetch(data.url)
        } else {
            return Promise.reject(data.msg)
        }
    }).then(res => res.json()).then(data => {
        Object.assign(item, data)
        item.id = id
        item.updateTime = Date.now()
        item.enabled = enabled
        ProjectService.save(item)
    }).catch(err => console.log(err))
}